/**
 *
 */
package com.iknight.mgr.controller;

import com.github.pagehelper.PageInfo;
import com.iknight.mgr.api.AttachmentService;
import com.iknight.mgr.core.base.BaseController;
import com.iknight.mgr.core.constant.IkgConstantCode;
import com.iknight.mgr.core.utils.IkgStringUtils;
import com.iknight.mgr.core.utils.IkgWebUtils;
import com.iknight.mgr.model.AttachmentModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tika.mime.MimeType;
import org.apache.tika.mime.MimeTypeException;
import org.apache.tika.mime.MimeTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.UUID;

/**
 * @author JeryZym
 */
@RestController
@RequestMapping("/rest/attachment")
@Api("附件管理类")
public class AttachmentController extends HttpServlet implements BaseController<AttachmentModel> {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Autowired
    private AttachmentService<AttachmentModel, String> attachmentService;

    @Value("${filePath}")
    private String filePath;

    @Value("${isSavedWithExtension}")
    private boolean isSavedWithExtension;

    @Override
    public AttachmentModel format(Map<String, Object> params) {
        return null;
    }

    @Override
    @PostMapping("/save")
    public Object save(@RequestBody Map<String, Object> params, HttpServletRequest request,
                       HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空!", IkgConstantCode.PARAMSNULL);
        }
        attachmentService.save(format(params));
        return IkgWebUtils.postIkgResponse(true, "保存成功!", IkgConstantCode.OPERSUCCESS);
    }

    @Override
    @PostMapping("/delete")
    public Object delete(@RequestBody Map<String, Object> params, HttpServletRequest request,
                         HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空!", IkgConstantCode.PARAMSNULL);
        }
        attachmentService.delete(IkgStringUtils.ObjectToString(params.get("attachment_id")));
        return IkgWebUtils.postIkgResponse(true, "删除成功!", IkgConstantCode.OPERSUCCESS);
    }

    @Override
    @PostMapping("/selectOne")
    public Object selectOne(@RequestBody Map<String, Object> params, HttpServletRequest request,
                            HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        AttachmentModel record = attachmentService.selectOne(IkgStringUtils.ObjectToString(params.get("attachment_id")));
        return IkgWebUtils.postIkgResponse(true, "查询成功", record);
    }

    @PostMapping("/abate")
    public Object abateFile(@RequestBody Map<String, Object> params, HttpServletRequest request,
                            HttpServletResponse response) {
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        return null;
    }

    @Override
    public boolean isPKeyNotNull(Map<String, Object> params) {
        // TODO Auto-generated method stub
        return params != null && params.get("attachment_id") != null;
    }

    @Override
    @PostMapping("/list")
    public Object selectByPage(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (params == null) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        int pageIndex = IkgStringUtils.ObjectToInt(params.get("pageNumber"));
        int pageSize = IkgStringUtils.ObjectToInt(params.get("pageSize"));
        PageInfo<AttachmentModel> files = attachmentService.selectPage(params, pageIndex, pageSize);
        return IkgWebUtils.postResult(files.getTotal(), files.getList());
    }

    @PostMapping("/uploadFile")
    @ApiOperation(value = "上传附件方法")
    public Object uploadFile(@RequestParam("files") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!file.isEmpty()) {
            String newFileId = UUID.randomUUID().toString();
            boolean result = uploadFile(file, newFileId);
            // 保存数据
            AttachmentModel record = new AttachmentModel();
            record.setAttachment_id(newFileId);
            record.setAttachment_name(file.getOriginalFilename());
            record.setAttachment_type(file.getContentType());
            record.setUpload_time(IkgStringUtils.getCurrentDate("yyyy-MM-dd HH:mm"));
            attachmentService.save(record);

            return IkgWebUtils.postIkgResponse(result, "上传" + (result ? "成功!" : "失败"), result);
        } else {
            return IkgWebUtils.postIkgResponse(false, "上传失败", false);
        }
    }

//    public Object uploadMultiFiles(@RequestParam("file") MultipartFile[] files, @RequestBody Map params,
//                                   HttpServletRequest request, HttpServletResponse response) throws IOException {
//        return null;
//    }

    public boolean uploadFile(CommonsMultipartFile file, String fileId) {
        File dir = new File(filePath + File.separator + "tmpFiles");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String ext = null;
        try {
            String contentType = file.getContentType();
            MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
            MimeType attachMentType = allTypes.forName(contentType);
            ext = attachMentType.getExtension();
            File serverFile = null;
            if (isSavedWithExtension) {
                serverFile = new File(dir.getAbsolutePath() + File.separator + fileId + (null == ext ? "" : ext));
            } else {
                serverFile = new File(dir.getAbsolutePath() + File.separator + fileId);
            }

            file.transferTo(serverFile);
            return true;
        } catch (IllegalStateException | IOException | MimeTypeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

//    public boolean uploadFile(MultipartFile file, String fileId) throws IOException {
//        InputStream in = null;
//        OutputStream out = null;
//        try {
//            File dir = new File(filePath + File.separator + "tmpFiles");
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            File serverFile = new File(dir.getAbsolutePath() + File.separator + fileId);
//            in = file.getInputStream();
//            out = new FileOutputStream(serverFile);
//            byte[] b = new byte[1024];
//            int len = 0;
//            while ((len = in.read(b)) > 0) {
//                out.write(b, 0, len);
//            }
//            out.close();
//            in.close();
//            return true;
//        } catch (IOException e) {
//            // TODO: handle exception
//            return false;
//        } finally {
//            if (out != null) {
//                out.close();
//                out = null;
//            }
//
//            if (in != null) {
//                in.close();
//                in = null;
//            }
//        }
//    }

    @GetMapping("/showPic")
    public void showPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/*");

        String picId = request.getParameter("picId");
        FileInputStream fis = new FileInputStream(filePath + File.separator + "tmpFiles" + File.separator + picId);
        OutputStream os = response.getOutputStream();
        try {
            int size = fis.available();
            byte[] buffer = new byte[size];
            fis.read(buffer);
            os.write(buffer);
            os.flush();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }

}
